package com.zyw.dev.zyw.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.zyw.dev.zyw.R;
import com.zyw.dev.zyw.dao.DaoMaster;
import com.zyw.dev.zyw.dao.DaoSession;
import com.zyw.dev.zyw.dao.ZJWBeans;
import com.zyw.dev.zyw.dao.ZJWBeansDao;
import com.zyw.dev.zyw.db.DataBaseHealper;
import com.zyw.dev.zyw.ui.fragment.MenuFragment;
import com.zyw.dev.zyw.ui.fragment.ZJWChartFragment;
import com.zyw.dev.zyw.ui.fragment.ZJWTableFragment;
import com.zyw.dev.zyw.utils.SMSTools;
import com.zyw.dev.zyw.utils.SPUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class MainActivity extends AppCompatActivity implements View.OnClickListener, MenuFragment.OnFragmentActionListener, ZJWTableFragment.OnFragmentInteractionListener {

    public static final String ACTION_INTENT_RECEIVER = "new.sms.receiver";

    private static final String FRAGMENT_TABLE = "table";

    private static final String FRAGMENT_CART = "cart";

    private static final String FRAGMENT_MENU = "menu";

    public static final String DATA_LIST_KEY = "data_list";

    private static final String READ_SMS = "read_sms";

    private FragmentManager fragmentManager;

    private FragmentTransaction fragmentTransaction;

    private ZJWChartFragment zjwChartFragment;

    private ZJWTableFragment zjwTableFragment;

    private MenuFragment menuFragment;

//    private Button btn_table, btn_chart;

    private int currentIndex = -1;

    private long mExitTime;

    private DataBaseHealper dataBaseHealper;

    private ImageView iv_close;

    private List<ZJWBeans> zjwBeansList = new ArrayList<>();

    private MessageReceiver mMessageReceiver;

    private TextView tv_login_user, tv_user_name;

    private String userName = "";

    private static boolean isFromLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentManager = getSupportFragmentManager();
        if (null != savedInstanceState) {
            zjwChartFragment = (ZJWChartFragment) fragmentManager.getFragment(savedInstanceState, FRAGMENT_CART);
            zjwTableFragment = (ZJWTableFragment) fragmentManager.getFragment(savedInstanceState, FRAGMENT_TABLE);
            menuFragment = (MenuFragment) fragmentManager.getFragment(savedInstanceState, FRAGMENT_MENU);
        }

        isFromLogin = getIntent().getBooleanExtra("isFromLogin", false);
        String loginCache = (String) SPUtils.get(this, LoginActivity.LOGIN_CACHE_KEY, "");
        if (loginCache.length()<=0){
            showWelcome();
            finish();
        }else{
            userName = loginCache.substring(0, loginCache.indexOf("@"));
            loginTime = (new Date().getTime() - Long.parseLong(loginCache.substring(loginCache.indexOf("@") + 1))) / 1000;
            initData();
            initConfig();
            initView();
            initFragments();
            registerMessageReceiver();
        }
    }

    private void showWelcome() {
        Intent intent = new Intent(this, WelcomeActivity.class);
        startActivity(intent);
        this.finish();
    }

    /**
     * 　　* onConfigurationChanged
     * 　　* the package:android.content.res.Configuration.
     * 　　* @param newConfig, The new device configuration.
     * 　　* 当设备配置信息有改动（比如屏幕方向的改变，实体键盘的推开或合上等）时，
     * 　　* 并且如果此时有activity正在运行，系统会调用这个函数。
     * 　　* 注意：onConfigurationChanged只会监测应用程序在AnroidMainifest.xml中通过
     * 　　* android:configChanges="xxxx"指定的配置类型的改动；
     * 　　* 而对于其他配置的更改，则系统会onDestroy()当前Activity，然后重启一个新的Activity实例。
     *
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 检测屏幕的方向：纵向或横向
        if (this.getResources().getConfiguration().orientation
                == Configuration.ORIENTATION_LANDSCAPE) {
            //当前为横屏， 在此处添加额外的处理代码
        } else if (this.getResources().getConfiguration().orientation
                == Configuration.ORIENTATION_PORTRAIT) {
            //当前为竖屏， 在此处添加额外的处理代码
        }
        //检测实体键盘的状态：推出或者合上
        if (newConfig.hardKeyboardHidden
                == Configuration.HARDKEYBOARDHIDDEN_NO) {
            //实体键盘处于推出状态，在此处添加额外的处理代码
        } else if (newConfig.hardKeyboardHidden
                == Configuration.HARDKEYBOARDHIDDEN_YES) {
            //实体键盘处于合上状态，在此处添加额外的处理代码
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isFromLogin) {
            showWelcome();
        }
//        isFromLogin = false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isFromLogin = false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        isFromLogin = false;
    }

    //在销毁时要与广播解绑
    @Override
    protected void onDestroy() {
        if (null != mMessageReceiver){
            unregisterReceiver(mMessageReceiver);
        }
        super.onDestroy();
    }

    private void initData() {
        dataBaseHealper = DataBaseHealper.newInstance();
        dataBaseHealper.initDataBase();

    }

    //    Gas concentration 14% Wind speed 29.9m/s Illumination 0.00Lx Humidity 00％RH Temperature 00C
    private void initConfig() {
        if (!SPUtils.contains(this, READ_SMS)) {
            //load sms from resms
            Cursor cursor = SMSTools.getSMSFromPhone(this);
            if (null == cursor) return;
            if (cursor.moveToFirst()) {
                do {
                    String body = cursor.getString(cursor.getColumnIndex("body"));
                    Date date = new Date(cursor.getLong(cursor.getColumnIndex("date")));

                    if (null == body || body.length() < 10) continue;
                    ZJWBeans beans = SMSTools.getZJWBeanBySMSBody(date, body);
                    zjwBeansList.add(beans);
                    Log.e("Tag::::", "" + dataBaseHealper.insert(beans));
                } while (cursor.moveToNext());
            }

            SPUtils.put(this, READ_SMS, "config");
        } else {
            //读取数据库.
            zjwBeansList = dataBaseHealper.read();
        }
    }

    private void initView() {
        iv_close = (ImageView) findViewById(R.id.iv_close);
        tv_login_user = (TextView) findViewById(R.id.tv_login_user);
        tv_user_name = (TextView) findViewById(R.id.tv_user_name);

        if (null != userName) {
            tv_user_name.setText(userName);
        }
        iv_close.setOnClickListener(this);

        new Thread(new MyThread()).start();
    }

    private void initFragments() {
        switchFramgnt(2);
    }

    protected void onSaveInstanceState(Bundle outState) {
        if (null != fragmentManager) {
            if (null != zjwTableFragment) {
                fragmentManager.putFragment(outState, FRAGMENT_TABLE, zjwTableFragment);
            }
            if (null != zjwChartFragment) {
                fragmentManager.putFragment(outState, FRAGMENT_CART, zjwChartFragment);
            }
            if (null != menuFragment) {
                fragmentManager.putFragment(outState, FRAGMENT_MENU, menuFragment);
            }
        }
        super.onSaveInstanceState(outState);
    }

    private void switchFramgnt(int index) {
        if (currentIndex == index) return;
        currentIndex = index;
        setPowerButton();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        hideFragments(fragmentTransaction);
        switch (index) {
            case 0:
                if (null == zjwTableFragment) {
                    zjwTableFragment = ZJWTableFragment.newInstance(zjwBeansList);
                    fragmentTransaction.add(R.id.fl_content, zjwTableFragment);

                } else {
                    fragmentTransaction.show(zjwTableFragment);
                }
                zjwTableFragment.setOnFragmentInteractionListener(this);
                break;
            case 1:
                if (null == zjwChartFragment) {
                    zjwChartFragment = ZJWChartFragment.newInstance(zjwBeansList);
                    fragmentTransaction.add(R.id.fl_content, zjwChartFragment);
                } else {
                    fragmentTransaction.show(zjwChartFragment);
                }
                break;
            case 2:
                if (null == menuFragment) {
                    menuFragment = MenuFragment.newInstance();

                    fragmentTransaction.add(R.id.fl_content, menuFragment);
                } else {
                    fragmentTransaction.show(menuFragment);
                }
                menuFragment.setOnFragmentActionListener(this);
                break;
        }
        fragmentTransaction.commit();
    }

    private void setPowerButton() {
        iv_close.setImageResource(currentIndex == 2 ? R.mipmap.ic_power : R.mipmap.ic_back);
    }

    private void hideFragments(FragmentTransaction ft) {

        if (null == ft) return;

        if (null != zjwTableFragment) {
            ft.hide(zjwTableFragment);
        }
        if (null != zjwChartFragment) {
            ft.hide(zjwChartFragment);
        }
        if (null != menuFragment) {
            ft.hide(menuFragment);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_table:
                switchFramgnt(0);
                break;
            case R.id.iv_close:
                if (menuFragment.isVisible()) {
                    goBack();
                } else {
                    switchFramgnt(2);
                }
                break;
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (menuFragment.isVisible()) {
                goBack();
            } else {
                switchFramgnt(2);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void goBack() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Object mHelperUtils;
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            SPUtils.put(this, LoginActivity.LOGIN_CACHE_KEY, "");
            finish();
//            System.exit(0);
        }
    }

    @Override
    public void onTableClicked() {
        switchFramgnt(0);
    }

    @Override
    public void OnChartClicked() {
        switchFramgnt(1);
    }

    private long loginTime = 0;
    final Handler handler = new Handler() {          // handle
        public void handleMessage(Message msg) {
            loginTime += 1;
            if (null != tv_login_user) {
                if (loginTime>5*60){
                    SPUtils.put(MainActivity.this, LoginActivity.LOGIN_CACHE_KEY, "");
                }
                tv_login_user.setText(String.format(getString(R.string.com_login_time), getLoginTimeFormat()));
            }
            super.handleMessage(msg);
        }
    };

    private String getLoginTimeFormat() {
        if (loginTime < 60) {
            return loginTime + "s";
        } else if (loginTime < 60 * 60) {
            return loginTime / 60 + "m" + loginTime % 60 + "s";
        } else if (loginTime < 24 * 60 * 60) {
            return (loginTime / (60 * 60)) + "h" + loginTime / 60 % 60 + "m" + loginTime % 60 + "s";
        } else {
            return loginTime + "s";
        }
    }

    @Override
    public void onDelete(ZJWBeans zjwBeans) {
        dataBaseHealper.delete(zjwBeans);
        if (zjwBeansList.contains(zjwBeans)) {
            zjwBeansList.remove(zjwBeans);
            updateZJWBeansList();
            Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
        }
    }

    public void updateZJWBeansList() {
        if (null != zjwChartFragment) {
            zjwChartFragment.setZJWBeanList(zjwBeansList);
        }
        if (null != zjwTableFragment) {
            zjwTableFragment.setZJWBeanList(zjwBeansList);
        }
    }

    public class MyThread implements Runnable {      // thread
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);     // sleep 1000ms
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                } catch (Exception e) {
                }
            }
        }
    }

    /**
     * 动态注册广播
     */
    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();

        filter.addAction(ACTION_INTENT_RECEIVER);
        registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            if (intent.getAction().equals(ACTION_INTENT_RECEIVER)) {
                Serializable serializable = intent.getSerializableExtra("data");
                if (null != serializable) {
                    ZJWBeans beans = (ZJWBeans) serializable;
                    zjwBeansList.add(0, beans);
                    updateZJWBeansList();
                }
            }
        }

    }
}
